package algorithm;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class QueryHtmlElement {


    /**
     * 获取指定HTML标签的指定属性的值(下标指针获取法)
     * @author ChenK
     * @param source 要匹配的源文本
     * @param element 标签名称
     * @param attr 标签的属性名称
     * @return 属性值列表
     */
    public static List<String> match(String source, String element, String attr) {
        //记录所有标签对的起止下标
        String source2 = source;
        List<int[]> indexList = new ArrayList<>();
        int startIndex;
        int endIndex;
        while (source2.length() > 0) {
            startIndex = source2.indexOf(element);
            if (startIndex == -1) {
                break;
            }
            endIndex = startIndex + element.length();
            while (endIndex < source2.length() && source2.charAt(endIndex) != '>') {
                endIndex++;
            }
            int[] arr = {startIndex, endIndex};
            indexList.add(arr);
            source2 = source2.substring(endIndex, source2.length());
        }
        //从标签对中取属性
        if (indexList.size() > 0) {
            List<String> retList = new ArrayList<>();
            Iterator<int[]> iterator = indexList.iterator();
            while (iterator.hasNext()) {
                int[] intArr = iterator.next();
                StringBuilder temp = new StringBuilder(source.substring(intArr[0], intArr[1]));
                //删除多余内容
                temp.delete(0, temp.indexOf(attr));
                temp.delete(0, temp.indexOf("\"") + 1);
                temp.delete(temp.lastIndexOf("\""), temp.length());
                retList.add(temp.toString());
            }
            return retList;
        }
        return new ArrayList<>(0);
    }
}
